package com.qdc.datacenters.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qdc.datacenters.domain.entity.BaseEntity;
import com.qdc.datacenters.domain.entity.SysUserDept;
import com.qdc.datacenters.domain.entity.SysUserRole;
import com.qdc.datacenters.mapper.SysUserDeptMapper;
import com.qdc.datacenters.service.ISysUserDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户部门关联表(SysUserDept)表服务实现类
 *
 * @author danmo
 * @since 2024-02-26 17:31:57
 */
@Service
public class SysUserDeptServiceImpl extends BaseServiceImpl<SysUserDeptMapper, SysUserDept> implements ISysUserDeptService {

    @Override
    public void updateBatch(Long userId, List<Long> deptIds) {
        //部门ID为空全部删除
        if (CollectionUtils.isEmpty(deptIds)) {
            update(new LambdaUpdateWrapper<SysUserDept>().set(BaseEntity::getDelFlag, 0).eq(SysUserDept::getUserId, userId));
            return;
        }
        List<SysUserDept> sysUserDepts = list(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getUserId, userId).eq(BaseEntity::getDelFlag, 0));
        //部门为空全部新增
        if (CollectionUtils.isEmpty(sysUserDepts)) {
            List<SysUserDept> sysUserDeptList = deptIds.stream().map(deptId -> {
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setUserId(userId);
                sysUserDept.setDeptId(deptId);
                return sysUserDept;
            }).collect(Collectors.toList());
            saveBatch(sysUserDeptList);
        } else {
            //需要删除部门
            List<Long> delIdList = sysUserDepts.stream().filter(sysUserDept -> !deptIds.contains(sysUserDept.getDeptId())).map(SysUserDept::getId).collect(Collectors.toList());
            update(new LambdaUpdateWrapper<SysUserDept>().set(BaseEntity::getDelFlag, 1).in(SysUserDept::getId, delIdList));
            //需要新增部门
            List<Long> addDeptIds = deptIds.stream().filter(deptId -> sysUserDepts.stream().noneMatch(sysUserDept -> Objects.equals(sysUserDept.getDeptId(), deptId))).collect(Collectors.toList());

            List<SysUserDept> addUserRoleList = addDeptIds.stream().map(deptId -> {
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setUserId(userId);
                sysUserDept.setDeptId(deptId);
                return sysUserDept;
            }).collect(Collectors.toList());
            saveBatch(addUserRoleList, 200);
        }
    }
}

